<template>
  <div class="container">
    <!-- 头部导航 -->
    <van-nav-bar
      title="小思同学"
      fixed
      left-arrow
      @click-left="$router.back()"
    />

    <!-- 聊天的主体区域 -->
    <div class="chat-list">
      <div v-for="(item, index) in list" :key="index">
        <div class="chat-item left" v-if="item.name === 'xs'">
          <van-image
            class="avator"
            round
            src="https://img01.yzcdn.cn/vant/cat.jpeg"
          >
          </van-image>
          <div class="chat-pao">
            {{ item.msg }}
          </div>
        </div>
        <div class="chat-item right" v-else>
          <div class="chat-pao">
            {{ item.msg }}
          </div>
          <van-image class="avator" round :src="userAvator"> </van-image>
        </div>
      </div>
    </div>

    <div class="reply-container">
      <van-field v-model.trim="word" placeholder="说点什么...">
        <template #button>
          <span @click="send()">提交</span>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
import { io } from 'socket.io-client'
import { mapGetters } from 'vuex'
// 定义变量 socket，用来存储 websocket 连接的实例对象（默认值 null 表示当前没有创建 websocket 连接）
let socket = null

export default {
  name: 'Chat',
  data() {
    return {
      // 用户输入的聊天内容
      word: '',
      // 所有的聊天的消息的集合 项，都是对象，格式为 { name,msg}
      list: []
    }
  },

  components: {},

  computed: {
    ...mapGetters(['userAvator'])
  },

  mounted() {
    // 调用io方法 创建websocket 连接
    socket = io('ws://www.liulongbin.top:9999')

    // 为 socket 连接对象，绑定 connect事件
    socket.on('connect', () => {
      console.log('已经连接到websocket连接了') // true
    })

    // 为 socket 连接对象，绑定 disconnect 事件
    socket.on('disconnect', () => {
      console.log('websocket连接已经断开') // false
    })
    // 为 socket 连接对象，绑定 message 事件
    socket.on('message', msg => {
      console.log('msg:', msg)
      this.list.push({ name: 'xs', msg })
    })
  },

  methods: {
    send() {
      // 调用 socket.emit('send', '消息的内容') 向服务器发送消息
      socket.emit('send', this.word)
      this.list.push({ name: 'me', msg: this.word })
      this.word = ''
    },
    scrollToBottom() {
      // 获取所有的聊天的条目的dom集合
      const items = document.querySelectorAll('.chat-item')
      // 获取最后一个dom节点
      const lastItem = items[items.length - 1]
      // 3. 调用 DOM 元素的 .scrollIntoView() 实现滚动效果
      lastItem.scrollIntoView({
        behavior: 'smooth',
        block: 'end'
      })
    }
  },
  watch: {
    list() {
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    }
  }
}
</script>
<style lang="less" scoped>
.container {
  padding: 94px 0 100px 0;
  height: 100%;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  background: #fafafa;
}
.chat-list {
  // height: 3000px;
  overflow-y: scroll;
  height: 100%;
  .chat-item {
    padding: 10px;
    display: flex;
    .avator {
      width: 80px;
      height: 80px;
    }
    .chat-pao {
      position: relative;
      min-width: 80px;
      max-width: 70%;
      line-height: 76px;
      border: 1px solid #c2d9ea;
      border-radius: 8px;
      background-color: #e0effb;
      font-size: 28px;
      color: #333;
      padding: 0 20px;
      &::before {
        content: '';
        width: 20px;
        height: 20px;
        position: absolute;
        top: 24px;
        border-top: 1px solid #c2d9ea;
        border-right: 1px solid #c2d9ea;
        background: #e0effb;
      }
    }
  }
  .left {
    text-align: left;
    .chat-pao {
      margin-left: 30px;
      &::before {
        left: -10px;
        transform: rotate(-135deg);
      }
    }
  }
  .right {
    text-align: right;
    justify-content: right;
    .chat-pao {
      margin-right: 30px;
      &::before {
        right: -10px;
        transform: rotate(45deg);
      }
    }
  }
}
.reply-container {
  position: fixed;
  bottom: 0;
  background: #f5f5f5;
  width: 100%;
  span {
    font-size: 24px;
    color: #999;
  }
}
</style>
